<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\api\model\ding;

use app\api\service\User as UserService;
use app\common\model\ding\Coupon as CouponModel;
use think\facade\Db;

/**
 * 用户余额变动明细模型
 * Class BalanceLog
 * @package app\api\model\user
 */
class Coupon extends CouponModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'store_id',
    ];

    /**
     * 获取账单明细列表
     * @return \think\Paginator
     * @throws \app\common\exception\BaseException
     * @throws \think\db\exception\DbException
     */
    public function getList($params)
    {

        // 获取列表数据
        return $this->alias('c')
            ->join('ding_coupon_category t', 't.category_id=c.coupon_type')
            ->where('c.shop_id', $params['shopId'])
            ->field('c.*,t.name as coupon_type_text')
            ->order(['c.create_time' => 'desc'])
            ->select()->toArray();
    }
    public function edit($data)
    {

        return $this->transaction(function () use ($data) {
            $expire_day = (int) $data['expire_day'];

            if ($expire_day > 0) {
                $data['start_time'] = strtotime(Date('Y-m-d'));
                $data['end_time']   = strtotime(Date('Y-m-d')) + 86400 * $expire_day;
            }

            $data['create_time'] = time();
            $data['store_id']    = self::$storeId;
            $this->save($data);

            return true;
        });
    }
    public function add($data)
    {
        $user    = UserService::getCurrentLoginUser(true);
        $clerkId = Db::name('store_shop_clerk')->where('user_id', $user['user_id'])->where('shop_id', $data['shop_id'])
            ->value('clerk_id');
        return $this->transaction(function () use ($data, $clerkId) {

            $expire_day = (int) $data['expire_day'];

            if ($expire_day > 0) {
                $data['start_time'] = strtotime(Date('Y-m-d'));
                $data['end_time']   = strtotime(Date('Y-m-d')) + 86400 * $expire_day;
            }

            $data['clerk_id']    = $clerkId;
            $data['create_time'] = time();
            $data['store_id']    = self::$storeId;
            $this->save($data);

            return true;
        });
    }

}
